package com.mrx.xfriendship.util;

import com.mrx.commons.util.JWTUtil;
import com.mrx.xfriendship.model.SecurityUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.function.Function;

/**
 * @author Mr.X
 * @since 2023-01-14 20:51
 */
public class SecurityUtil {

    /**
     * 刷新当前用户的 token
     */
    public static String getCurrentUserToken() {
        return JWTUtil.getToken(getCurrentUserName());
    }

    public static String getCurrentUserName() {
        return withPrincipal(SecurityUser.class, SecurityUser::getName);
    }

    public static Integer getCurrentUserId() {
        return withPrincipal(SecurityUser.class, SecurityUser::getId);
    }

    public static String getCurrentUserRole() {
        return withPrincipal(SecurityUser.class, SecurityUser::getRole).get(0);
    }

    /**
     * 获取当前登录的用户信息并用其作为参数执行 function, 返回 function 的返回值
     *
     * @param targetPrincipal 预期 Principal 对象
     * @param function        要执行的函数
     */
    @SuppressWarnings("unchecked")
    public static <T, R> R withPrincipal(Class<T> targetPrincipal, Function<T, R> function) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null || !principal.getClass().equals(targetPrincipal))
            throw new IllegalStateException("Principal 类型有误: " + principal);
        return function.apply((T) principal);
    }

    /**
     * 设置当前登录的用户
     */
    public static void setAuthentication(Authentication authentication) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

}
